package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service("iuserService")
public class IUserServiceimpl  implements IUserService{

    @Autowired
    UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {

        int resultCount = userMapper.checkUsername(username);

        if ( resultCount == 0){
            return ServerResponse.createByErrorMessage("无此用户");
        }

        String md5pad = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username,md5pad);

        if( user == null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",user);
    }

    @Override
    public ServerResponse<String> register(User user) {

        ServerResponse servervalid = this.checkValid(user.getUsername(),Const.USERNAME);

        if( !servervalid.isSuccess()){
            return servervalid;
        }
        servervalid = this.checkValid(user.getEmail(),Const.EMAIL);
        if( !servervalid.isSuccess()){
            return  servervalid;
        }

        user.setRole(Const.Role.ROLE_CUSTOMER);

        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

       int  resultCount = userMapper.insert(user);

        if( resultCount ==0 ){
            return ServerResponse.createByErrorMessage("注册失败");
        }


        return ServerResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ServerResponse<String> checkValid(String str, String type) {

        if( StringUtils.isNotBlank(type)){

            if( Const.USERNAME.equals(type) ){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMessage("用户名存在");
                }
            }

            if( Const.EMAIL.equals(type))  {
                int resultCount = userMapper.checkEmail(str);
                if( resultCount > 0){
                    return  ServerResponse.createByErrorMessage("邮箱存在");
                }
            }

        }
        else{
           return ServerResponse.createByErrorMessage("参数错误");
        }

        return ServerResponse.createBySuccessMessage("校验成功");
    }

    @Override
    public ServerResponse<String> selectQuestion(String username) {

        ServerResponse valiResponse = this.checkValid(username,Const.USERNAME);
        if( valiResponse.isSuccess() ){
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        String question = userMapper.selectQuestionByUsername(username);

        if( StringUtils.isNotBlank(question)){
            return ServerResponse.createBySuccess(question);
        }

        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    @Override
    public ServerResponse<String> checkAnswer(String username, String question, String answer) {

        int reslutCount = userMapper.checkAnswer(username,question,answer);

        if(reslutCount > 0){
            String forgenToken  = UUID.randomUUID().toString();

            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgenToken);
            return  ServerResponse.createBySuccess(forgenToken);

        }

        return ServerResponse.createByErrorMessage("问题的答案错误");
    }

    @Override
    public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){

        if( StringUtils.isNotBlank(forgetToken)){
                return ServerResponse.createByErrorMessage("参数错误，token需要传值");
        }
        ServerResponse validResponse = this.checkValid(username,passwordNew);

        if( validResponse.isSuccess()){
            return  ServerResponse.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);

        if( StringUtils.isNotBlank(token) ){
            return  ServerResponse.createByErrorMessage("token无效，或者过期");
        }
        if( StringUtils.equals(forgetToken,token)){

            String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);

            int resultCount = userMapper.updatePasswordByUsername(username,md5Password);
            if( resultCount > 0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }

        }else{
            return ServerResponse.createByErrorMessage("token错误,请重新获取重置密码");
        }
        return  ServerResponse.createByErrorMessage("修改密码失败");

    }

    @Override
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user) {

        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),user.getId());

        if( resultCount == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }

        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(  updateCount > 0 ){
            return  ServerResponse.createBySuccessMessage("更新密码成功");
        }

        return ServerResponse.createByErrorMessage("更新密码失败");
    }

    @Override
    public ServerResponse<User> updateInformation(User user) {
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());

        if( resultCount > 0){
            return  ServerResponse.createByErrorMessage("email已经存在，请更换email");
        }

        User updateUser = new User();

        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if( updateCount > 0) {
            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);

        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    @Override
    public ServerResponse<User> getInformation(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if( user == null){
            return  ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return  ServerResponse.createBySuccess(user);
    }

    /**
     * 校验是否为管理员
     * @param user
     * @return
     */
    @Override
    public ServerResponse checkAdminRole(User user) {
        if( user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN ){
            return ServerResponse.createBySuccess();
        }

        return ServerResponse.createByError();
    }


}
